package com.rasou;

import com.rasou.jms.Constant;
import com.rasou.jms.JmsListener;
import org.geektimes.event.EventListener;
import org.geektimes.event.distributed.DistributedEventObject;
import org.geektimes.event.reactive.stream.ListenerSubscriberAdapter;
import org.geektimes.reactive.streams.SimplePublisher;

import java.util.Date;
import java.util.EventObject;
import java.util.concurrent.TimeUnit;


public class DistributedEventPublisher {

    private final SimplePublisher<EventObject> simplePublisher = new SimplePublisher<>();

    public DistributedEventPublisher(EventListener listener) {
        addEventListener(listener);
    }


    public void addEventListener(EventListener eventListener) {
        simplePublisher.subscribe(new ListenerSubscriberAdapter(eventListener));
    }

    public void publish(Object event){
        simplePublisher.publish(new DistributedEventObject(event));
    }

    public static void main(String[] args) throws InterruptedException {
        DistributedEventPublisher eventPublisher =  getJMSDistributedEventPublisher();
        eventPublisher.publish("第一条消息："+ new Date());
        TimeUnit.SECONDS.sleep( 5 );
        eventPublisher.publish("第二条消息："+ new Date());
        TimeUnit.SECONDS.sleep( 5 );
        eventPublisher.publish("第三条消息："+ new Date());
    }

    private static DistributedEventPublisher getJMSDistributedEventPublisher() {
        DistributedEventPublisher eventPublisher = new DistributedEventPublisher(
                new JmsListener( Constant.URL ) );
        return eventPublisher;
    }

}
